<?php
/**
 * Created by PhpStorm.
 * User: DongYao
 * Date: 2017/12/18
 * Time: 下午9:36
 */

namespace XmtApp\Modules\Admin\Controllers\Api;


use App\Exceptions\ApiException;
use App\Http\Requests\DevicePost;
use App\Http\Resources\DeviceResource;
use App\Http\Resources\DevicesResource;
use App\Rules\LadderPriceRule;
use App\Support\Device\QRCodeExport;
use App\Tables\Device;
use App\Tables\Expressions\GeoEntry;
use App\Tables\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use XmtApp\Modules\Admin\Controllers\Controller;
use PHPExcel_Worksheet_Drawing;

use DB;
use Excel;
use Storage;


class DeviceController extends Controller
{
    public $user;

    public function __construct()
    {
        parent::__construct();

        $this->user = Auth::guard('api')->user();
    }

    /**
     * 查询设备列表
     * @param Request $request
     * @return DevicesResource
     */
    public function index(Request $request)
    {
        $query = new Device();

        /**
         * 级联查询下级代理
         */
        if ($request->filled('parent_agent_id')) {
            $query = $query->ofChildren($request->parent_agent_id);
        } else {
            if ($this->user->hasRole('agent')) {
                $query = $query->ofChildren($this->user->id);
            }
        }

        /**
         * 设置查询条件
         */
        if ($request->filled('province_code')) {
            $query = $query->where('province_code', $request->province_code);
        }

        if ($request->filled('city_code')) {
            $query = $query->where('city_code', $request->city_code);
        }

        if ($request->filled('district_code')) {
            $query = $query->where('district_code', $request->district_code);
        }

        if ($request->filled('created_at') && is_array($request->created_at)) {
            $query = $query->whereBetween('created_at', $request->created_at);
        }

        if ($request->filled('status')) {
            $query =$query->where('status', $request->status);
        }

        if ($request->filled('keyword')) {
            $query = $query->where(function($query) use ($request) {
                $query->orWhere('device_sn', 'like', "%{$request->keyword}%");
                $query->orWhere('name', 'like', "%{$request->keyword}%");
                $query->orWhere('address', 'like', "%{$request->keyword}%");
                $query->orWhereHas('agent', function ($query) use ($request) {
                    $query->where('realname', 'like', "%{$request->keyword}%");
                });
            });
        }

        if ($request->get('is_export') == 'yes') {
            $data = $query->paginate($request->header('pageSize'));
            $info = $this->exportQrcode($data);

            if (isset($info['file'])) {
                $info['url'] = url('storage/exports/' . $info['file']);
                return response()->json(ajax_return(true, '导出成功', $info));
            } else {
                return response()->json(ajax_return(false, '导出失败', [$data]));
            }
        }

        $query = $query->orderBy('created_at', 'desc');

        $data = $query->paginate($request->header('pageSize'));

        return new DevicesResource($data);
    }

    /**
     * 添加设备
     * @param DevicePost $post
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(DevicePost $post)
    {
        /**
         * 验证修改权限
         */
        if (!$this->user->hasRole('agent') && $this->user->extension->agent_level !== 3) {
            new ApiException('只允许3级代理可以添加设备');
        }

        $device = new Device();
        $device->user_id    = $this->user->id;
        $device->device_sn  = $device->autoMakeDeviceSn();
        $device->name       = $post->name;
        $device->province_code  = $post->province_code;
        $device->city_code      = $post->city_code;
        $device->district_code  = $post->district_code;
        $device->address        = $post->address;
        $device->coordinate     = new GeoEntry($post->coordinate);
        $device->status         = 'offline';
        $device->ports          = ['p1' => 0,'p2' => 0,'p3' => 0,'p4' => 0,'p5' => 0,'p6' => 0];
        $device->ladder_price   = $post->ladder_price;
        $device->remark         = $post->remark;


        if ($device->save()) {
            return response()->json(ajax_return(true, '添加成功', new DeviceResource($device)));
        }

        return response()->json(ajax_return(false, '添加失败'));
    }

    /**
     * 批量添加设备
     * @param $number
     * @param DevicePost $post
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchCreate($number, DevicePost $post)
    {
        /**
         * 验证修改权限
         */
        if (!$this->user->hasRole('agent') && $this->user->extension->agent_level !== 3) {
            new ApiException('只允许3级代理可以添加设备');
        }

        /**
         * 验证设备批量添加个数
         */
        if ($number > 2000 || $number < 1) {
            new ApiException('单次可添加1~2000个设备');
        }

        DB::transaction(function () use ($post, $number) {
            $device = new Device();

            $data = [];
            for ($i = 1; $i <= $number; $i++) {
                $data[] = [
                    'user_id'        => $this->user->id,
                    'device_sn'      => $device->autoMakeDeviceSn(),
                    'name'           => $post->name,
                    'province_code'  => $post->province_code,
                    'city_code'      => $post->city_code,
                    'district_code'  => $post->district_code,
                    'address'        => $post->address,
                    'coordinate'     => DB::raw((new GeoEntry($post->coordinate))->getValue()),
                    'status'         => 'offline',
                    'ports'          => json_encode(['p1' => 0,'p2' => 0,'p3' => 0,'p4' => 0,'p5' => 0,'p6' => 0]),
                    'ladder_price'   => json_encode($post->ladder_price),
                    'remark'         => $post->remark,
                    'created_at'     => Carbon::now(),
                    'updated_at'     => Carbon::now()
                ];
            }

            $device->insert($data);
        });

        return response()->json(ajax_return(true, '添加成功'));
    }

    /**
     * 修改设备信息
     * @param $id
     * @param DevicePost $post
     * @return \Illuminate\Http\JsonResponse
     */
    public function update($id, DevicePost $post)
    {
        /**
         * 验证修改权限
         */
        $device = Device::find($id);

        if ($this->user->id !== $device->user_id) {
            new ApiException('这个不是你的设备，不能修改！');
        }

        $device->name       = $post->name;
        $device->province_code  = $post->province_code;
        $device->city_code      = $post->city_code;
        $device->district_code  = $post->district_code;
        $device->address        = $post->address;
        $device->coordinate     = new GeoEntry($post->coordinate);
        $device->ladder_price   = $post->ladder_price;
        $device->remark         = $post->remark;

        if ($device->save()) {
            return response()->json(ajax_return(true, '修改成功', new DeviceResource($device)));
        }

        return response()->json(ajax_return(false, '修改失败'));
    }

    /**
     * 获取设备信息
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($id)
    {
        $device = Device::find($id);

        if (empty($device)) {
            return response()->json(ajax_return(false, '获取设备信息失败'));
        }

        return response()->json(ajax_return(true, '获取订单信息成功', new DeviceResource($device)));
    }

    /**
     * 批量设置三级代理所属的所有设备定价策略
     * @param $agent_user_id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiException
     */
    public function batchUpdateLadderPrice($agent_user_id, Request $request)
    {
        $agent = User::where('id', $agent_user_id)->first();
        if (empty($agent)) {
            throw new ApiException('代理用户不存在');
        }

        if ($agent->extension->agent_level != 3) {
            throw new ApiException('代理用户不存在');
        }

        /**
         * 验证参数
         */
        $this->validate($request, [
            'ladder_price' => new LadderPriceRule()
        ]);

        $res = Device::where('user_id', $agent_user_id)->update(['ladder_price' => json_encode($request->ladder_price)]);
        if ($res) {
            return response()->json(ajax_return(true, '批量设置3级代理所属的设备定价成功'));
        }

        return response()->json(ajax_return(false, '批量设置3级代理所属的设备定价失败'));
    }

    /**
     * 导出二维码列表
     * @param $list
     */
    private function exportQrcode($list) {
        $cell_data = [];
        foreach ($list as $item) {
            $cell_data[] = $item->device_sn;
        }

        $rows_data = collect($cell_data)->chunk(5)->toArray();

        return Excel::create('设备二维码-' . date('YmdHis'),function($excel) use ($rows_data){
            $excel->sheet('二维码', function($sheet) use ($rows_data){
                $sheet->setColumnFormat(array(
                    'A' => '@',
                    'B' => '@',
                    'C' => '@',
                    'D' => '@',
                    'E' => '@',
                ));

                $sheet->setWidth(array(
                    'A'     =>  30,
                    'B'     =>  30,
                    'C'     =>  30,
                    'D'     =>  30,
                    'E'     =>  30,
                ));

                $cell_name = ['A', 'B', 'C', 'D', 'E'];
                foreach ($rows_data as $row =>  $cells) {
                    $cells = array_values($cells);
                    foreach ($cells as $column => $cell_data) {
                        $cell_pos = $cell_name[$column] . ($row + 1);

                        $sheet->cell($cell_pos, function ($cell) use ($cell_data) {
                            $cell->setValue(" ". $cell_data);
                        });

                        $qrcode = new QRCodeExport();
                        $qrcode_path = $qrcode->setSize(800)
                            ->setLogoFileRealPath(resource_path('assets/js/webapp/images/logo.jpg'))
                            ->setUrl(rtrim(env('APP_URL'), '/') . '/webapp/#/device/detail?device_sn=' . $cell_data)
                            ->saveQRCodeFile($cell_data, true);

                        $objDrawing = new PHPExcel_Worksheet_Drawing;
                        $objDrawing->setPath($qrcode_path);
                        $objDrawing->setCoordinates($cell_pos);
                        $objDrawing->setWidth(150);
                        $objDrawing->setWidth(150);
                        $objDrawing->setResizeProportional(false);
                        $objDrawing->setOffsetX(30);
                        $objDrawing->setOffsetY(20);
                        $objDrawing->setRotation(0);
                        $objDrawing->setWorksheet($sheet);

                        $sheet->getRowDimension($row+1)->setRowHeight(150);
                    }
                }

                $sheet->cells('A1:E' . count($rows_data), function($cells) {
                    $cells->setFontSize(12);
                    $cells->setAlignment('center');
                });

            });
        })->save('xls', false, true);
    }
}